/**
 * java抛异常机制(Throwable)
 * 
 * 1. Error  java虚拟出错，抛出的异常
 * 2. Exception
 *  - 运行时异常RuntimeException (uncheck exception)    比如：NullPointerException
 *  - 非运行时异常(check exception) 比如：IllegalAccessException NegativeArraySizeException  EmptyStackException
 */
package java06;

import java.util.EmptyStackException;

/**
 * @author chen_jintao
 *
 */
public class Stack {

	private int[] stack;
	private int top;
	/**
	 * 构造函数
	 */
	public Stack(int size) {
		// TODO Auto-generated constructor stub
		stack = new int[size];
		top = 0;
	}
	
	/**
	 * 出栈函数，空栈时抛出运行时异常EmptyStackException
	 */
	public int pop() {
		if(top == 0) {
			throw new EmptyStackException();
		}
		top--;
		int iterm = stack[top];
		return iterm;
	}
	
	/**
	 * 压栈函数，栈满时抛出自定义异常OutOfStackException
	 */
	public void push(int iterm) throws OutOfStackException {
		if(top == stack.length) {
			throw new OutOfStackException(top);
		}
				
		stack[top] = iterm;
		top++;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Stack s = new Stack(5);
		
		//必须捕获非运行时异常
		try {
			s.push(1);
			s.push(2);
			s.push(3);
			s.push(4);
			s.push(5);
			s.push(6);
		} catch (OutOfStackException e) {
			// TODO Auto-generated catch block
			System.out.println("栈push溢出，栈length:"+ e.getLength());
			e.printStackTrace();
		}
		
		//可以不用捕获运行时异常
		for (int i = 0; i < 6; i++) {
			System.out.println(s.pop());
		}
	}

}
